import { useState } from 'react';
import { Sender, Suggestion } from '@ant-design/x';
import { Flex } from 'antd';
import BubbleList from './BubbleList';
import OpenAI from 'openai';

interface Message {
  key: string;
  role: 'user' | 'assistant';
  content: string;
  loading?: boolean;
}

const ChatWindow = () => {
  const [value, setValue] = useState('');
  const [messages, setMessages] = useState<Message[]>([]);

  const client = new OpenAI({
    apiKey: 'sk-ef8d6eea58ba4318a19399ea3e0d08c3',
    baseURL: 'https://api.deepseek.com',
    dangerouslyAllowBrowser: true,
  });

  const handleSubmit = async (message: string) => {
    if (message.trim()) {
      // 添加用户消息
      setMessages([...messages, { key: Date.now().toString(), role: 'user', content: message }]);
      
      setValue('');

      // 发送消息并等待回复
      try {
        const resultMsg = await sendChatMes(message);
        // 添加助手消息
        setMessages((prevMessages) => [
          ...prevMessages,
          { key: Date.now().toString(), role: 'assistant', content: resultMsg || '' }
        ]);
      } catch (error) {
        console.error('Error fetching response:', error);
        setMessages((prevMessages) => [
          ...prevMessages,
          { key: Date.now().toString(), role: 'assistant', content: 'An error occurred while fetching the response.' }
        ]);
      }

    }
  };

  async function sendChatMes(message: string) {
    const completion = await client.chat.completions.create({
      messages: [{ role: 'user', content: message }],
      model: 'deepseek-reasoner',
    });

    console.log(completion.choices[0].message.content);
    return completion.choices[0].message.content;
  }

  return (
    <Flex vertical style={{ flex: 1, height: '100%' }} gap={8}>
      {/* 聊天记录 */}
      <BubbleList items={messages} />

      {/* 快捷指令 */}
      <Suggestion
        items={[
          {
            label: 'Write a report',
            value: 'report',
          },
        ]}
      >
        {({ onTrigger, onKeyDown }) => (
          <>
            {/* 输入框 */}
            <Sender
              value={value}
              onChange={(nextVal) => {
                if (nextVal === '/') {
                  onTrigger();
                } else if (!nextVal) {
                  onTrigger(false);
                }
                setValue(nextVal);
              }}
              onSubmit={handleSubmit}
              onKeyDown={onKeyDown}
              placeholder='Type "/" to trigger suggestion'
            />
          </>
        )}
      </Suggestion>
    </Flex>
  );
};

export default ChatWindow;